package com.ucar.achievement.service.impl;

import com.google.common.collect.Lists;
import com.ucar.achievement.callback.CustomPaginationBuilderCallback;
import com.ucar.achievement.dao.AchieveAdjustDao;
import com.ucar.achievement.dao.AchievementDao;
import com.ucar.achievement.dao.AchievementHisDao;
import com.ucar.achievement.enums.AchievementEnum;
import com.ucar.achievement.form.*;
import com.ucar.achievement.model.*;
import com.ucar.achievement.pojo.AchievementHisPojo;
import com.ucar.achievement.pojo.AchievementPojo;
import com.ucar.achievement.service.AchievementPostService;
import com.ucar.achievement.service.AchievementService;
import com.ucar.achievement.util.AchievementDetailUtil;
import com.ucar.achievement.util.AchievementFormBuilder;
import com.ucar.base.cdms.dto.ManualAchievementOrderQueryDTO;
import com.ucar.base.cdms.dto.ManualAchievementOrderQueryRe;
import com.ucar.base.common.Result;
import com.ucar.base.common.resultUtil.RemoteCommConstant;
import com.ucar.base.ucarcodriver.common.CodriverAchievementConstant.OrderCommissionStatusEnum;
import com.ucar.common.util.DateUtils;
import com.ucar.util.NumberUtil;
import com.ucar.util.RemoteClientUtils;
import com.zuche.framework.backdoor.util.JsonUtils;
import com.zuche.framework.remote.RemoteClientFactory;
import com.zuche.framework.sys.exception.BizException;
import org.apache.commons.lang.StringUtils;
import org.jmesa.limit.Limit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service("achievementServceImpl")
public class AchievementServiceImpl implements AchievementService {

	private final static Logger logger = LoggerFactory.getLogger(AchievementServiceImpl.class);

	private final static String UNLOCK_ACHIEVEMENT = "ucarcodriver.achievement.driveros.V1.unlock";

	private final static String MANUAL_ACHIEVEMENT_QUERY_ORDER_LIST = "ucarcdms.order.queryOrderListForManualAchievement";

	private final static String MANUAL_ACHIEVEMENT = "ucarcodriver.achievement.driveros.V1.manualAchievement";

	@Autowired
	private AchievementDao achievementDao;

	@Autowired
	private AchieveAdjustDao achieveAdjustDao;

	@Autowired
	private AchievementHisDao achievementHisDao;
	@Autowired
	private AchievementPostService achievementPostService;
	@Autowired
	private AchievementDetailUtil achievementDetailUtil;
	@Autowired
	private AchievementFormBuilder achievementFormBuilder;

	@Override
	public List<AchievementVO> getAchieveList(AchievementForm achievement) {
		return achievementDao.queryAchieveList(achievement);
	}

	@Override
	public List<ManualAchievementOrderQueryRe> queryOrderListForManualAchievement(ManualAchievementForm achievement) {
		// 参数处理
		if(StringUtils.isBlank(achievement.getOrderNo())) {
			achievement.setOrderNo(null);
		}
		if(StringUtils.isBlank(achievement.getCreateTimeStart())) {
			achievement.setCreateTimeStart(null);
		}
		if(StringUtils.isBlank(achievement.getCreateTimeEnd())) {
			achievement.setCreateTimeEnd(null);
		} else {
			achievement.setCreateTimeEnd(DateUtils.formatDate(DateUtils.addMinute(DateUtils.convertDate(achievement.getCreateTimeEnd(), DateUtils.DATETIME_PATTERN_SHORT), 1), DateUtils.DATETIME_PATTERN));
		}

		List<String> orderNoList = achievementDao.selectOrderListForManualAchievement(achievement);
		String alreadyOrderNos = StringUtils.join(orderNoList, ",");
		try {
			ManualAchievementOrderQueryDTO manualAchievementOrderQueryDTO = new ManualAchievementOrderQueryDTO();
			if(StringUtils.isNotBlank(achievement.getDriverMobile())) {
				manualAchievementOrderQueryDTO.setDriverMobile(achievement.getDriverMobile());
			}
			if(null != achievement.getDriverId()) {
				manualAchievementOrderQueryDTO.setDriverId(achievement.getDriverId());
			}
			if(StringUtils.isNotBlank(achievement.getOrderNo())) {
				manualAchievementOrderQueryDTO.setOrderNo(achievement.getOrderNo());
			}
			if(StringUtils.isNotBlank(alreadyOrderNos)) {
				manualAchievementOrderQueryDTO.setAlreadyOrderNos(alreadyOrderNos);
			}
			if(StringUtils.isNotBlank(achievement.getCreateTimeStart())) {
				manualAchievementOrderQueryDTO.setCreateTimeStart(DateUtils.convertDate(achievement.getCreateTimeStart(), DateUtils.DATETIME_PATTERN_SHORT));
			}
			if(StringUtils.isNotBlank(achievement.getCreateTimeEnd())) {
				manualAchievementOrderQueryDTO.setCreateTimeEnd(DateUtils.convertDate(achievement.getCreateTimeEnd(), DateUtils.DATETIME_PATTERN_SHORT));
			}
			Result<List<ManualAchievementOrderQueryRe>> result = (Result<List<ManualAchievementOrderQueryRe>>)
					RemoteClientUtils.executeToObject(MANUAL_ACHIEVEMENT_QUERY_ORDER_LIST, manualAchievementOrderQueryDTO);
			if(result.getRe() == null) {
				return Lists.newArrayList();
			}
			return result.getRe();
		} catch (Exception e) {
			logger.error("AchievementServiceImpl queryOrderListForManualAchievement error,achievement:" + JsonUtils.jsonEncode(achievement), e);
			return Lists.newArrayList();
		}
	}

	@Override
	public Result manualAchievement(String orderNo) {
		Result result = (Result) RemoteClientUtils.executeToObject(MANUAL_ACHIEVEMENT, orderNo);
		return result;
	}

	@Override
	public List<AchievementVO> getAchieveListByPage(AchievementForm achievement) {
		return achievementDao.queryAchieveListByPage(achievement);
	}

	@Override
	public Integer getAchieveListCount(AchievementForm achievement) {
		return achievementDao.queryAchieveListCount(achievement);
	}

	@Override
	public AchievementDetailVO getAchieveInfo(AchievementForm achievement) {
		logger.debug("AchievementServiceImpl getAchieveInfo start,achievement={}",JsonUtils.jsonEncode(achievement));
		//查询业绩信息
		final AchievementVO achievementVO = achievementDao.queryAchieveById(achievement);
		final Long achievementId = achievementVO.getId();

		final AchieveAdjustForm achieveAdjustForm = this.achievementFormBuilder.buildAchieveAdjustForm(new CustomPaginationBuilderCallback<AchieveAdjustForm>() {
			@Override
			public void before(AchieveAdjustForm achieveAdjustForm) {
				achieveAdjustForm.setAchievementId(achievementId);
			}

			@Override
			public Limit getLimit() {
				return new Limit("orderQueryTable");
			}
		});

		final AchievementPostParam achievementPostParam = this.achievementFormBuilder.buildAchievementPostParam(new CustomPaginationBuilderCallback<AchievementPostParam>() {
			@Override
			public void before(AchievementPostParam achievementPostParam) {
				achievementPostParam.setAchievementId(achievementId);
			}

			@Override
			public Limit getLimit() {
				return new Limit("orderQueryTable");
			}
		});
		//1、获取调整列表
		final Pagination<AchAdjustmentVO> adjustListPagination = new Pagination<AchAdjustmentVO>(20,1,achieveAdjustDao.queryListAdjustCount(achieveAdjustForm),achieveAdjustDao.queryListAdjustByPage(achieveAdjustForm));
		final Pagination<AchievePostVO> postListPagination = new Pagination<AchievePostVO>(20,1,achievementPostService.queryCount(achievementPostParam),achievementPostService.queryListByPage(achievementPostParam));
		//创建详情VO对象、封装：业绩VO、调整累计VO、入账累计VO、调整列表分页VO、入账列表分页VO
		return this.achievementDetailUtil.buildVO(new AchievementDetailUtil.InitCallback() {
			@Override
			public AchievementVO getAchievementVO() {
				return achievementVO;
			}

			@Override
			public AchievementPostSumVO getPostSumVO() {
				return achievementPostService.querySumVo(achievementId).setScaleForView();
			}

			@Override
			public AchievementAdjustSumVO getAdjustSumVO() {
				AchievementAdjustSumVO achAdjustmentVO = achieveAdjustDao.queryAdjustSumVo(achieveAdjustForm);
				return new AchievementAdjustSumVO(achAdjustmentVO.getCommissionAmountTotal(),achAdjustmentVO.getAdvanceAmountTotal(),
						achAdjustmentVO.getTaxAmountTotal(),achAdjustmentVO.getArrearageAmountTotal()).setScaleForView();
			}

			@Override
			public Pagination<AchAdjustmentVO> getAdjustListPagination() {
				return adjustListPagination;
			}

			@Override
			public Pagination<AchievePostVO> getPostListPagination() {
				return postListPagination;
			}
		});
	}

	@Override
	public void lockCommission(Long orderId) {
		logger.error("AchievementServiceImpl lockCommission start,orderId:" + orderId);
		AchievementPojo achievementPojo = achievementDao.selectAchievementByOrderId(orderId);
		// 进行提成释放操作时，如果服务订单状态为已完成，则释放后自动入账；如果不是已完成状态，则需要等到自动任务执行时才能入账
		achievementPojo.setCommissionStatus(OrderCommissionStatusEnum.LOCKED.getValue());
		// 更新订单业绩
		achievementDao.updateAchievementSelectiveByOrderId(achievementPojo);


		// 释放成功后，生成订单业绩的历史操作记录
		AchievementHisPojo achievementHisPojo = new AchievementHisPojo();
		achievementHisPojo.setCommissionStatus(OrderCommissionStatusEnum.LOCKED.getValue());
		achievementHisPojo.setRemark(AchievementEnum.AchAdjustHOption.LOCK.getName());
		buildHistoryPojo(achievementPojo, achievementHisPojo);
		achievementHisDao.insertAchievementHis(achievementHisPojo);
	}

	@Override
	public void unlockCommission(Long orderId) throws Exception {
		logger.info("AchievementServiceImpl lockCommission start,orderId:" + orderId);
		try {
			RemoteClientUtils.executeToObject(UNLOCK_ACHIEVEMENT, orderId);
		} catch (Exception e) {
			logger.error("AchievementServiceImpl lockCommission focus an exception,orderId={}:",orderId,e);
			throw e;
		}
	}

	/**
	 * 构建操作历史记录
	 * @param achievementPojo
	 * @param achieveHisPojo
	 */
	public void buildHistoryPojo(AchievementPojo achievementPojo, AchievementHisPojo achieveHisPojo) {
		// 保存一条订单业绩操作历史
		achieveHisPojo.setCommissionAmount(achievementPojo.getAchievementCommission());
		achieveHisPojo.setAdjustAmount(new BigDecimal(0));
		achieveHisPojo.setOrderId(achievementPojo.getOrderId());
		achieveHisPojo.setOrderStatus(achievementPojo.getOrderStatus());
		achieveHisPojo.setModifyEmp(achievementPojo.getModifyEmp());
		achieveHisPojo.setModifyTime(achievementPojo.getModifyTime());
		achieveHisPojo.setEstimateBoardTime(achievementPojo.getEstimateBoardTime());
	}

	@Override
	public AchievementVO getAchieveInfoById(AchievementForm achievement) {
		logger.debug("AchievementServiceImpl lockCommission start,achievement:" + JsonUtils.jsonEncode(achievement));
		return achievementDao.queryAchieveById(achievement);
	}
}
